﻿#pragma once
#include "ZContainer.h"
#include "ZCaret.h"
#include "ZTextDocument.h"

namespace ZuiLib
{

//代表一行
struct ZTextEditRow
{
	int m_width;//该行的宽度
	ZCharRange m_range;//字符的范围 minPos <= ch <maxPos
};

//TODO:添加撤回功能
class ZTextEdit:public ZContainer
{
public:
	ZUI_CLASS_NAME("zui.TextEdit");
	ZTextEdit();
	~ZTextEdit();

	const char* GetClass() const ZOVERRIDE;
	void* GetInterface(const char* pstrName) ZOVERRIDE;

	void SetTextColor(color_t dwTextColor);
	color_t GetTextColor() const;
	void SetDisabledTextColor(color_t dwTextColor);
	color_t GetDisabledTextColor() const;

	void SetFontName(const char* font);
	const char* GetFontName();

	ZFreeTypeFontPtr GetFont();

	RECT GetTextPadding() const;
	void SetTextPadding(RECT rc);

	void DoEvent(TEventUI& event) ZOVERRIDE;
	void SetAttribute(const char* pstrName, const char* pstrValue) ZOVERRIDE;

	void PaintText(ZRenderer* render) ZOVERRIDE;

	ZString GetText() const ZOVERRIDE;
	void SetText(const char* pstrText) ZOVERRIDE;
	void AppendText(const char* pstrText);

	int GetLineCount() const;


	int LineFromPos(POINT pt);
	POINT PosFromLine(int nLine);

	//根据字符索引位置获取行数
	int LineFromChar(int nChar);

	//获取该行字符开始位置
	int LineIndex(int nLine) const;

	//获取该行字符数
	int LineLength(int nLine) const;

	//通过鼠标位置获取字符索引
	int CharFromPos(POINT pt);
	POINT PosFromChar(int nCh);

	int TextWidth(int nChBegin,int nChEnd);

	void SetPos(RECT rc) ZOVERRIDE;
	void SetScrollPos(SIZE szPos) ZOVERRIDE;
	void SetLinePadding(int linePadding) { m_linePadding = linePadding; }

	void SetReadOnly(bool readonly);
	void Copy();
	void Cut();
	void Paste();
	void SelAll();
	void SelNone();
	void Undo();

	void HomeUp() ZOVERRIDE;
	void EndDown() ZOVERRIDE;

	void SetFontSize(int fontSize) { m_nFontSize = fontSize; Invalidate(); }
	int GetFontSize() const { return m_nFontSize; }

	void NeedUpdate();

	//Signal
	sigslot::signal1<ZTextEdit*> SignalTextChanged;
protected:
	DISALLOW_COPY_AND_ASSIGN(ZTextEdit);

	void PaintTextBk(ZRenderer* render);
	void PaintTextEditing(ZRenderer* render);

	void LayoutRow(int width);//计算字符行
	RECT GetCaretRect();
	void SetCaretPos(POINT pt);

	void RemoveSel();
	void RemoveEditing();
	void NeedUpdateCaret();
	void ScrollToCaret();//滚动到光标位置，确保光标可见

	uint32_t m_uState;

	bool m_needUpdateCaret;
	bool m_needScrollToCaret;

	ZTextDocument  m_doc;
	ZRefCountedPtr<ZCaret> m_caret;

	//保存edit的行信息
	std::vector<ZTextEditRow> m_rows;

	int m_selBegin;
	int m_selEnd;
	int m_caretPos;

	//正在编辑的文字
	int m_editingBegin;
	int m_editingEnd;
	int m_editingOffset;


	int m_linePadding;//行间距
	bool m_readOnly;
	ZString m_sFont;
	int         m_nFontSize;
	color_t m_dwTextColor;
	color_t m_dwDisabledTextColor;
	RECT m_rcTextPadding;
	int  m_currentWidth;
};

}
